package com.css.common.core.utils;

import com.css.common.core.constant.ErrorCodeConstants;
import com.css.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RefreshScope
@Component
public class PasswordUtils {

    private static PasswordUtils passwordUtils;

    private String passwordComplexity;

    @Value("${mhzc.passwordComplexity:1}")
    private void setPasswordComplexity(String property){
        this.passwordComplexity = property;
    }

    @PostConstruct
    public void init(){
        passwordUtils = this;
        passwordUtils.passwordComplexity = this.passwordComplexity;
    }


    @EventListener
    public void onRefreshScopeRefreshed(final RefreshScopeRefreshedEvent event) {
        getClass();
    }

    public static void passwordCheck(String password){
        if (GyUtils.isNull(password)){
            throw new ServiceException(ErrorCodeConstants.PASSWORD_CHECK_NULL.getMsg());
        }

        //不可包含中文
        if (containsChinese(password)){
            throw new ServiceException(ErrorCodeConstants.PASSWORD_CHECK_CHINESE.getMsg());
        }
        
        if ("1".equals(passwordUtils.passwordComplexity)){
            //一级密码复杂度 限制8个以上字符
            if (password.length()<8){
                throw new ServiceException(ErrorCodeConstants.PASSWORD_CHECK_FIRST.getMsg());
            }
        }

        if ("2".equals(passwordUtils.passwordComplexity)){
            //二级密码复杂度 一级安全基础上要求三种字符格式
            final String secondReg = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z!@#$%^&*()_+,.<>/?`~]+$)(?![a-z0-9]+$)(?![a-z!@#$%^&*()_+,.<>/?`~]+$)(?![0-9!@#$%^&*()_+,.<>/?`~]+$)[a-zA-Z0-9!@#$%^&*()_+,.<>/?`~]{8,}$";
            if (!password.matches(secondReg)){
                throw new ServiceException(ErrorCodeConstants.PASSWORD_CHECK_SECOND.getMsg());
            }
        }

        if ("3".equals(passwordUtils.passwordComplexity)){
            //三级密码复杂度 二级基础上要求字母必须有大小写和包含只少一个特殊字符
            final String thirdReg = "^[a-zA-Z!@#$%^&*()_+,.<>/?`~]{8,}$";
            if (!password.matches(thirdReg)){
                throw new ServiceException(ErrorCodeConstants.PASSWORD_CHECK_THIRD.getMsg());
            }
        }
    }

    public static boolean containsChinese(String password) {
        Pattern pattern = Pattern.compile("[一-龥]");
        Matcher matcher = pattern.matcher(password);
        return matcher.find();
    }

}
